import os
import sys
from pathlib import Path
import yaml

BASE_DIR = Path(__file__).resolve().parent


class ImproperlyConfigured(Exception):
    """Server is somehow improperly configured"""
    pass


CONFIG_PATH = os.path.join(BASE_DIR, 'config.yaml')
# 从配置文件更新
if os.path.exists(CONFIG_PATH):
    with open(CONFIG_PATH, "r") as f:
        config_dict = yaml.load(f.read(), Loader=yaml.FullLoader)
else:
    sys.stderr.write(f"请确认配置文件{CONFIG_PATH}是否存在!! 配置文件信息请见 README.MD#Configuration\n")


def _get_config(field, default=None):
    if field in config_dict.keys():
        return config_dict[field]
    else:
        if default is None:
            raise ImproperlyConfigured(f"缺失必须的配置信息 {field}")
        else:
            sys.stderr.write(f"缺失配置信息{field}，现使用默认值{default}.\n")
            return default


SPLIT_CONFIG_FILE = _get_config('split_config_file')
VOCAB_CONFIG_FILE = _get_config('vocab_config_file')
MODEL_CONFIG_FILE = _get_config('model_config_file')
